#include <QStringList>
#include "oxford-3000-updater.h"
#include "network-error.h"
#include "parse-error.h"

using namespace Oxford;

List3000Updater::List3000Updater() : QObject(), QRunnable()
{
    databaseManager = new Core::DatabaseManager("Oxford");
}

List3000Updater::~List3000Updater()
{
    delete databaseManager;
}

void List3000Updater::run()
{
    emit updateStarted();
    emit logMessage("Oxford 3000 update started");

    QStringList resultList;

    try
    {
        QStringList letterPages = oxfordLoader.loadOxford3000LettersList();

        for (QStringList::const_iterator letterPage = letterPages.constBegin(); letterPage != letterPages.constEnd(); letterPage++)
        {
            int pageId = 1;
            QStringList words;
            do
            {
                words = oxfordLoader.loadOxford3000ListPage(*letterPage, pageId);
                resultList.append(words);
                pageId++;
            } while  (!words.isEmpty());
        }

        databaseManager->storeList("Oxford3000", resultList);
    }
    catch(Core::ENetworkError e)
    {
        emit logError(e.fullMessage());
    }
    catch (Core::EParseError e)
    {
        emit logError(e.fullMessage());
    }
    catch(...)
    {
        emit logError("Unknown update error");
    }

    emit logMessage("Oxford 3000 update finished");
    emit updateFinished();
}
